package com.learn.sunday.auth.configure;

import com.learn.sunday.auth.filter.WithTokenRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    protected WithTokenRequestFilter withTokenRequestFilter;


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
//                .authorizeRequests().antMatchers("/*").permitAll()
                .authorizeRequests().antMatchers("/VIID/System/Register","/VIID/System/Keepalive","/auth/v1/login","/auth/v1/users","/tool/v1/timestamp").permitAll()
                .antMatchers("/findUser").hasAnyRole("admin")
                .antMatchers("/iot/v1/rule").hasAnyAuthority("9527")
                .anyRequest().authenticated().and()
                .exceptionHandling().authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized")).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        httpSecurity.addFilterBefore(withTokenRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
